package sealte.hvpms.dao.impl;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.util.ArrayList;
import java.util.List;

import sealte.hvpms.dao.RulesDAO;
import sealte.hvpms.pojo.Rule;
import sealte.hvpms.util.DBConnection;

public class RulesDAOImpl implements RulesDAO {
	Connection conn = null;
	PreparedStatement ps = null;
	ResultSet rs = null;
		
	public List<Rule> getAll(){
		List<Rule> all = new ArrayList<Rule>();
		String sql = "select * from hvpms_rules";
		try{
			conn = DBConnection.getConnection();
			ps = conn.prepareStatement(sql);
			rs = ps.executeQuery();
			while(rs.next()){
				Rule rule = new Rule();
				rule.setId(rs.getInt("rule_id"));
				rule.setContent(rs.getString("rule_content"));
				rule.setIsUsed(rs.getString("rule_isused"));
				all.add(rule);
			}
		}catch(Exception e){
			e.printStackTrace();
		}finally{
			DBConnection.close(rs, ps, conn);
		}
		return all;
	}
	
	public boolean changeIsUsed(String isused,int id){
		boolean flag = false;
		String sql = "update hvpms_rules set rule_isused=? where rule_id=?";
		try{
			conn = DBConnection.getConnection();
			ps = conn.prepareStatement(sql);
			ps.setString(1, isused);
			ps.setInt(2, id);
			ps.executeUpdate();
			flag = true;
		}catch(Exception e){
			e.printStackTrace();
		}finally{
			DBConnection.close(null, ps, conn);
		}
		return flag;
	}
	
	public boolean deleteRuleByID(int id){
		boolean flag = false;
		String sql = "delete from hvpms_rules where rule_id=?";
		try{
			conn = DBConnection.getConnection();
			ps = conn.prepareStatement(sql);
			ps.setInt(1, id);
			ps.executeUpdate();
			flag = true;			
		}catch(Exception e){
			e.printStackTrace();
		}finally{
			DBConnection.close(null, ps, conn);
		}
		return flag;
	}
	
	public String getContentByID(int id){
		String content = "";
		String sql = "select rule_content from hvpms_rules where rule_id=?";
		try{
			conn = DBConnection.getConnection();
			ps = conn.prepareStatement(sql);
			ps.setInt(1, id);
			rs = ps.executeQuery();
			if(rs.next()){
				content = rs.getString("rule_content");
			}
		}catch(Exception e){
			e.printStackTrace();
		}finally{
			DBConnection.close(rs, ps, conn);
		}
		return content;
	}
}
